package net.ojbk.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/3/21
 * Time: 16:59
 * Description: No Description
 */
public class AutoDaoTool {
    // 读取XML模板
    private static String mappingXMLFileTemplate = "";

    static {
        mappingXMLFileTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org/DTD Mapper 3.0\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<!--①修改与接口全限定类名一致-->\n" +
                "<mapper namespace=\"{{classPath}}\">\n" +
                " \n" +
                "    <!--②id与接口定义的方法名一致-->\n" +
                "    <select id=\"selectAll\" resultType=\"{{className}}\">\n" +
                "        SELECT {{attributes}} FROM `{{tableName}}`\n" +
                "    </select>\n" +
                "\n" +
                "    <insert id=\"insertOne\" parameterType=\"{{className}}\">\n" +
                "        INSERT INTO `{{tableName}}`({{attributes}})\n" +
                "        VALUES({{#{attribute}s}})\n" +
                "    </insert>\n" +
                "\n" +
                "    <delete id=\"deleteOne\" parameterType=\"{{className}}\">\n" +
                "        DELETE FROM `{{tableName}}`\n" +
                "        WHERE {{PrimaryKey}} = #{{{PrimaryKey}}}\n" +
                "    </delete>\n" +
                "\n" +
                "    <update id=\"updateOne\" parameterType=\"{{className}}\">\n" +
                "        UPDATE `{{tableName}}`\n" +
                "        SET {{attribute=#{attribute}s}}\n" +
                "        WHERE {{PrimaryKey}} = #{{{PrimaryKey}}}\n" +
                "    </update>\n" +
                "\n" +
                "</mapper>" +
                "\n";
    }

    public static void autoDao(String poPath, String daoPath) throws Exception {
        // 校验下路径
        File dirPo = new File(poPath);
        File dirDao = new File(daoPath);
        if (!dirPo.exists() || !dirDao.exists())
            throw new Exception("This poPath or daoPath are wrong");
        // 计算packagePath
        String packagePath_po = poPath.substring(poPath.indexOf("main\\java\\") + 10).replace("\\", ".");
        String packagePath_dao = daoPath.substring(daoPath.indexOf("main\\java\\") + 10).replace("\\", ".");
        for (File file_poJava : dirPo.listFiles()) {
            String fileName = file_poJava.getName();
            if (!fileName.endsWith(".java"))
                continue;
            System.out.println(fileName);
            String className = fileName.substring(0, fileName.indexOf("."));
            boolean isHadXML = false;
            for (File file_daoJava : dirDao.listFiles()) {
                String fileName_tempDaoXML = file_daoJava.getName();
                if (!fileName_tempDaoXML.endsWith(".xml"))
                    continue;
                if ((className + "Dao.xml").equals(fileName_tempDaoXML))
                    isHadXML = true;
            }
            if (!isHadXML) {
                // 没有创建过
                AutoDaoTool.createNewXML(packagePath_po + "." + className, daoPath, packagePath_dao);
            }
        }
    }

    /**
     * Creat Mapping XML file.
     *
     * @param className       et. net.ojbk.common.beans.po.User
     * @param destinationPath et. D:\javaIdea\one\common\src\main\java\net\ojbk\common\dao
     */
    public static void createNewXML(String className, String destinationPath, String packagePath_dao) throws Exception {
        Class aClass = Class.forName(className);
        String classSimpleName = aClass.getSimpleName();

        // 构造替换
        StringBuffer buff_attributes = new StringBuffer();
        String tableName = classSimpleName.substring(0, 1).toLowerCase() + classSimpleName.substring(1);
        StringBuffer buff_attribute_s = new StringBuffer();
        String primaryKet = "`id`";
        StringBuffer buff_attribute_attribute_s = new StringBuffer();

        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            buff_attributes.append(",`" + field.getName() + "` ");
            buff_attribute_s.append(",#{" + field.getName() + "} ");
            buff_attribute_attribute_s.append(",`" + field.getName() + "`=#{" + field.getName() + "} ");
        }
        buff_attributes.delete(0,1);
        buff_attribute_s.delete(0,1);
        buff_attribute_attribute_s.delete(0,1);

        // 替换
        String newMapper = mappingXMLFileTemplate.replace("{{attributes}}", buff_attributes.toString())
                .replace("{{tableName}}", tableName)
                .replace("{{#{attribute}s}}", buff_attribute_s.toString())
                .replace("{{PrimaryKey}}", primaryKet)
                .replace("{{attribute=#{attribute}s}}", buff_attribute_attribute_s.toString())
                .replace("{{classPath}}", packagePath_dao + "." + classSimpleName + "Dao")
                .replace("{{className}}", classSimpleName);
        // 输出
        System.out.println(destinationPath + "/" + classSimpleName + "Dao.xml");
        FileOutputStream outputStream = new FileOutputStream(new File(destinationPath + File.separator+ classSimpleName + "Dao.xml"));
        OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
        writer.append(newMapper);
        writer.flush();
        writer.close();
        outputStream.close();
    }

    public static void main(String[] args) {
        String poPath = "D:\\javaIdea\\one\\common\\src\\main\\java\\net\\ojbk\\common\\beans\\po";
        String daoPath = "D:\\javaIdea\\one\\common\\src\\main\\java\\net\\ojbk\\common\\dao";
        try {
            AutoDaoTool.autoDao(poPath, daoPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
